package sbu.cs;

import sbu.cs.asdb.ASDBUtils;
import sbu.cs.ui.widget.MainMenu;
import sbu.cs.ui.widget.UserIdView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Main extends Activity implements IUserIdChangeObserver, IMessageObserver {
    /** Called when the activity is first created. */
	private static final String LOG_TAG = "Main::Debug";
	
	private LinearLayout rootLayout; 
	private Settings settings;
	private MainMenu mainMenu;
	private UserIdView userIDView; 
	private String dialogMessage;
	private ViewStack viewStack = ViewStack.createViewStack();
	private static final int DIALOG_SHOW_MESSAGE = 300;
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(LOG_TAG,intent.getAction());
			String[] res = intent.getStringArrayExtra("val");
			if(res.length > 0)
				dialogMessage = res[0];
			showDialog(DIALOG_SHOW_MESSAGE);
		}
	};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(LOG_TAG,"onCreate");
        setContentView(R.layout.main);
        
        // Initialize settings class
        settings = Settings.getPreferenceManager(this);
        ASDBUtils.createASDBUtils();
        rootLayout = new LinearLayout(getApplicationContext());
        rootLayout.setBackgroundResource(R.drawable.background_a);
        viewStack.pushView(rootLayout);
        
        Settings.getPreferenceManager(null).setLastMessage(Settings.DEF_LAST_MESSAGE);
        mainMenu = new MainMenu(this, "Send Vircast", "Receive Vircast", "Undo Last Vircast", "Delete My Vircasts");
        mainMenu.setMessageObserver(this);
        rootLayout.addView(mainMenu);
        viewStack.pushView(mainMenu);
        
        IntentFilter intentFilter = new IntentFilter("sbu.cs.MESSAGE_RCEIVED");
        registerReceiver(mReceiver, intentFilter);
        if(!settings.isUserIdSet()){
        	Log.i(LOG_TAG,"Device Not registered");
        	
        	mainMenu.setVisibility(View.GONE);
        	userIDView = new UserIdView(getApplicationContext());
        	userIDView.setUserIdChangeObserver(this);
        	rootLayout.addView(userIDView);
        	viewStack.pushView(userIDView);
        }else{
        	settings.startService();
        }
        setContentView(rootLayout);  
        
    }
    @Override
	public void onUserIdChanged(String userId, String password, boolean updateDB) {
		Log.i(LOG_TAG,userId);
		settings.setUserId(userId);
		if(updateDB)
			ASDBUtils.createASDBUtils().populateUserData(userId, password);
		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
		inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
		mainMenu.setVisibility(View.VISIBLE);
		userIDView.setVisibility(View.GONE);
		viewStack.popView();
		rootLayout.bringToFront();
		
	}
	@Override
	public void onReceive(String message) {
		dialogMessage = message;
		showDialog(DIALOG_SHOW_MESSAGE);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		TextView textView = new TextView(this);
		textView.setText(dialogMessage);
		return new AlertDialog.Builder(this)
        .setIcon(R.drawable.alert_dialog_icon)
        .setTitle("Vircast")
        //.setMessage(dialogMessage)
        .setView(textView)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                /* User clicked OK so do some stuff */
            	
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                /* User clicked OK so do some stuff */
            	
            }
        })
        .create();
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		TextView textView = new TextView(this);
		textView.setText(dialogMessage);
		textView.setTextSize(20);
		textView.setBackgroundColor(Color.BLACK);
		dialog.setContentView(textView);
		super.onPrepareDialog(id, dialog);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
		stopService(new Intent(this, VircastDaemon.class));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.i(LOG_TAG,"onResume");
		String intentString = getIntent().getAction();
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
		
		notificationManager.cancel(Settings.NOTIFICATION_ID);
        if(intentString != null)
        	Log.i(LOG_TAG,"onResume intentString: " + intentString);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.i(LOG_TAG,"keyDown: " + keyCode);
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		Log.i(LOG_TAG,"onBackPressed: ");
		if(!mainMenu.onBackPressed())
			super.onBackPressed();
	}
}